package com.tsfyun.scm.service.impl.system;

import cn.hutool.core.lang.Snowflake;
import com.google.common.collect.Lists;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.common.base.security.SecurityUtil;
import com.tsfyun.scm.entity.system.SysRoleMenu;
import com.tsfyun.scm.mapper.system.SysRoleMenuMapper;
import com.tsfyun.scm.service.system.ISysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleMenuServiceImpl  extends ServiceImpl<SysRoleMenu> implements ISysRoleMenuService {


    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    private Snowflake snowflake;

    @Override
    public void saveOrUpdate(String roleId, List<String> menuIdList) {
        deleteByRoleId(roleId);
        if(CollectionUtils.isEmpty(menuIdList)) {
            return;
        }

        //保存角色与菜单关系（调整为批量保存）
        List<SysRoleMenu> saveList = Lists.newArrayListWithExpectedSize(menuIdList.size());
        for(String menuId : menuIdList){
            SysRoleMenu sysRoleMenuE = new SysRoleMenu();
            sysRoleMenuE.setId(snowflake.nextId());
            sysRoleMenuE.setMenuId(menuId);
            sysRoleMenuE.setRoleId(roleId);
            sysRoleMenuE.setDateCreated(LocalDateTime.now());
            sysRoleMenuE.setCreateBy(SecurityUtil.getCurrentPersonIdAndName());
            sysRoleMenuE.setDateUpdated(sysRoleMenuE.getDateCreated());
            sysRoleMenuE.setUpdateBy(sysRoleMenuE.getCreateBy());
            saveList.add(sysRoleMenuE);
        }
        super.savaBatch(saveList);
    }

    @Override
    public List<String> queryMenusByRoleId(String roleId) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setRoleId(roleId);
        List<SysRoleMenu> sysRoleMenus = super.list(sysRoleMenu);
        if(CollectionUtils.isEmpty(sysRoleMenus)) {
            return null;
        }
        return sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByRoleId(String roleId) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setRoleId(roleId);
        super.remove(sysRoleMenu);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteBatchByRoleIds(List<String> roleIds) {
        return sysRoleMenuMapper.deleteBatchByRoleIds(roleIds);
    }

}
